package me.fung.rem.app.main

import me.fung.keen.app.view.Presenter
import me.fung.keen.component.message.msg
import me.fung.rem.app.GlobalState
import me.fung.rem.app.encryptor
import me.fung.rem.bean.repo.*
import mu.KotlinLogging
import java.text.SimpleDateFormat
import java.util.*


class MainPresenter : Presenter() {
    private val logger = KotlinLogging.logger { }
    fun loadConfig() {
        logger.info { "loadConfig" }
        GlobalState.hasKey = configPassword.isNotBlank()
    }

    fun autoSign() {
        if (!configAutoSignUp) {
            logger.info { "未启用自动登录" }
            return
        }

        val calendar = Calendar.getInstance()
        calendar.setTime(configLastLogin)
        calendar.add(Calendar.DATE, configAutoLoginDate)
        if (Date() > calendar.time) {
            logger.info { "自动登录已过期,上次登录：${configLastLogin},允许天数：${configAutoLoginDate}" }
            msg.send { info("自动登录已过期") }
            return
        }

        val localPassword = if (configCacheInput == "") "" else encryptor().decrypt(configCacheInput)
        if (GlobalState.passwordEncryptor().checkPassword(localPassword, configPassword)) {
            GlobalState.authorized = true
            msg.done()
            configLastLogin = Date()
            logger.info { "登录成功 " + SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(configLastLogin) }
        } else {
            msg.send { error("密码错误") }
        }

    }
}